import { navigateTo, showLoading, showToast, setNavigationBarTitle, showModal } from '@tarojs/taro';
import {
  QUERY_FTD_FOR_ADD_FLOW,
  QUERY_FLOW_BY_COND_ATTR,
} from '/@/api/modules/flow-path/flow-path-template';
import { FIND_ONE, SAVE, DELETE } from '/@/api/modules/flow-path/flow-path-draft';
import { INSERT_APP_FLOW_PATH_RECORD } from '/@/api/modules/flow-path/flow-path';
import { state } from '../state';
import { traverseFlowGraphCheckPersons, resultList } from './approve-person-check';
import dayjs from 'dayjs';
import { LOGIN_APP } from '/@/api/modules/base/app-sys-user';
import { appEvents } from '/@/utils/events';
import { QUERY_APP_FLOW_PATH_RECORD_DETAIL } from '/@/api/modules/flow-path/flow-path';
/**
 * 查询审批模版详情
 * @param id 审批id
 */
function queryDetail(id: string, approvedId?: string) {
  showLoading();
  QUERY_FTD_FOR_ADD_FLOW({ id }).then((res) => {
    state.templateName = res.flowpathTemplateDto?.templateName || '模版名称';
    setNavigationBarTitle({
      title: `${state.templateName}`,
    });
    state.templateId = res.flowpathTemplateDto?.id || '';
    state.attributes = res.flowpathTemplateDto?.attributes;
    state.flowGraph = res.flowpathTemplateDto?.flowGraph;
    state.flowGraphAddFlow = res.flowpathTemplateDto?.flowGraphAddFlow;
    state.flowGraphList = res.flowpathTemplateDto?.flowGraphList;
    state.conditionAttr = res.flowpathTemplateDto?.conditionAttr;
    state.conditionVattrCodeList = res.flowpathTemplateDto?.conditionVattrCodeList;
    setExtendConditionAttributes(); //设置条件分支属性
    //设置权限属性，且属性长度==属性配置长度
    if (
      res.flowpathTemplateDto &&
      res.flowpathTemplateDto.releaseUserAttrCfgList &&
      res.flowpathTemplateDto.attributes &&
      res.flowpathTemplateDto.releaseUserAttrCfgList.length > 0 &&
      res.flowpathTemplateDto.releaseUserAttrCfgList.length ===
        res.flowpathTemplateDto.attributes.length
    ) {
      setExtendAttributes(res.flowpathTemplateDto.releaseUserAttrCfgList);
    } else {
      setDefaultExtendAttributes();
    }
    //设置属性默认值
    setAttributeDefaultValue();
    if (approvedId) {
      queryApprovedDetail(approvedId);
    } else {
      //查询草稿
      queryDraft(id);
    }
  });
}

/**
 * 详情页默认属性
 */
function setDefaultExtendAttributes() {
  state.attributes?.forEach((item) => {
    item.readonlyAble = 2;
    item.editAble = 1;
    item.hiddenAble = 2;
  });
}

/**
 * 设置条件分支属性
 */
function setExtendConditionAttributes() {
  state.attributes?.forEach((item) => {
    if (item.attributeCode && state.conditionVattrCodeList?.includes(item.attributeCode)) {
      item.isCondition = true;
    }
  });
}

/**
 * 设置属性权限: 可读/可写/隐藏 扩展属性
 */
function setExtendAttributes(releaseUserAttrCfgList: FlowPathTemplateApi.ReleaseUserAttrCfgDTO[]) {
  releaseUserAttrCfgList.forEach((item) => {
    const attribute = state.attributes?.find((subItem) => subItem.id === item.attributeId);
    if (attribute) {
      attribute.readonlyAble = item.readonlyAble || 2;
      attribute.editAble = item.editAble || 1;
      attribute.hiddenAble = item.hiddenAble || 2;
    }
  });
}

function setAttributeDefaultValue() {
  state.attributes?.forEach((item) => {
    //1-单行输入框，4-多行输入框，5-数字输入框
    if (
      (item.attributeType === 1 || item.attributeType === 4 || item.attributeType === 5) &&
      item.editAble === 1 &&
      item.attributeDefault
    ) {
      item.attributeValue = item.attributeDefault;
    }

    //页面-可编辑-默认值-显示-结果
    //单选是 code_1，多选是 code_1,code_2,code_3 ，没有空格
    //6-单选框
    if (item.attributeType === 6 && item.editAble === 1 && item.attributeDefault) {
      item.attributeValue = item.attributeDefault;
    }

    //页面-可编辑-默认值-显示-结果
    //多选是 code_1,code_2,code_3
    //7-多选框
    if (item.attributeType === 7 && item.editAble === 1 && item.attributeDefault) {
      item.attributeValue = item.attributeDefault;
    }
    //页面-可编辑-默认值-显示-结果
    //3-日期
    if (item.attributeType === 3 && item.editAble === 1 && item.attributeDefault) {
      if (item.attributeDateFormat === 'yyyy-MM-dd') {
        //"attributeDefault": "1702396800000",
        item.attributeValue = dayjs(Number(item.attributeDefault)).format('YYYY-MM-DD');
      } else {
        item.attributeValue = dayjs(Number(item.attributeDefault)).format('YYYY-MM-DD HH:mm:ss');
      }
    }
    //11-部门选择
    if (item.attributeType === 11 && item.editAble === 1) {
      defaultDepartment(item);
    }
  });
}

function defaultDepartment(item: FlowPathTemplateApi.AttributeExtendDto) {
  showLoading();
  LOGIN_APP().then((res) => {
    if (res.organDtos && res.organDtos.length > 0) {
      const organ = res.organDtos[0];
      const obj = { id: organ.id, name: organ.name };
      item.attributeValue = JSON.stringify(obj);
    }
  });
}

/**
 * 提交审批,跳转到成功页面的时候能跳回定制页面
 * @param from:custom 来自定制页面/custom-single
 *
 */
function submit(from?: string) {
  const errorAttributeItem = state.attributes?.find((item) => {
    //可编辑/默认可编辑-属性为value空的情况
    //必须字段才有必要验证
    return (
      (!item.editAble || item.editAble === 1) &&
      item.attributeRequired === 1 &&
      !item.attributeValue
    );
  });
  //校验可编辑字段-属性value不能为空
  if (errorAttributeItem) {
    console.log('errorAttributeItem', errorAttributeItem);
    showToast({ title: `请填写${errorAttributeItem.attributeName}`, icon: 'error' });
    return;
  }
  //清空数据
  resultList.splice(0, resultList.length);
  //校验审批/抄送人员添加
  traverseFlowGraphCheckPersons(state.flowGraphAddFlow);
  console.log('resultList', resultList);
  const isFullAdd = resultList.every((item) => {
    return item;
  });
  //校验审批流程中的人员不能为空
  if (!isFullAdd) {
    showToast({ title: '请添加审批人员', icon: 'error' });
    return;
  }

  showLoading();
  INSERT_APP_FLOW_PATH_RECORD({
    flowpathRecordDto: {
      templateId: state.templateId,
      attributes: state.attributes,
    },
    flowGraph: state.flowGraph,
    flowGraphAddFlow: state.flowGraphAddFlow,
    flowGraphList: state.flowGraphList,
  }).then((res) => {
    if (res.comResp?.code === 100) {
      navigateTo({
        url: `/pages/approve/submit-success/index?templateName=${state.templateName}${
          from ? `&from=${from}` : ''
        }`,
      }).then(() => {
        clearData();
        deleteDraft(state.templateId);
      });
    }
  });
}

/**
 * 提交审批,跳转到成功页面的时候能跳回定制页面
 * @param from:edit/record
 *
 */
function submitByCustomSingle(title?: string, from?: string) {
  const errorAttributeItem = state.attributes?.find((item) => {
    //可编辑/默认可编辑-属性为value空的情况
    //必须字段才有必要验证
    return (
      (!item.editAble || item.editAble === 1) &&
      item.attributeRequired === 1 &&
      !item.attributeValue
    );
  });
  //校验可编辑字段-属性value不能为空
  if (errorAttributeItem) {
    console.log('errorAttributeItem', errorAttributeItem);
    showToast({ title: `请填写${errorAttributeItem.attributeName}`, icon: 'error' });
    return;
  }
  //清空数据
  resultList.splice(0, resultList.length);
  //校验审批/抄送人员添加
  traverseFlowGraphCheckPersons(state.flowGraphAddFlow);
  console.log('resultList', resultList);
  const isFullAdd = resultList.every((item) => {
    return item;
  });
  //校验审批流程中的人员不能为空
  if (!isFullAdd) {
    showToast({ title: '请添加审批人员', icon: 'error' });
    return;
  }

  showLoading();
  INSERT_APP_FLOW_PATH_RECORD({
    flowpathRecordDto: {
      templateId: state.templateId,
      attributes: state.attributes,
    },
    flowGraph: state.flowGraph,
    flowGraphAddFlow: state.flowGraphAddFlow,
    flowGraphList: state.flowGraphList,
  }).then((res) => {
    if (res.comResp?.code === 100) {
      navigateTo({
        url: `/pages/custom-approve-single/submit-success/index?title=${title}${
          from ? '&from=' + from : ''
        }`,
      }).then(() => {
        clearData();
        deleteDraft(state.templateId);
      });
    }
  });
}

//清理数据
function clearData() {
  state.attributes?.forEach((item) => {
    //1-单行输入框，4-多行输入框，5-数字输入框
    //2-图片 8-签名
    if (
      (item.attributeType === 1 ||
        item.attributeType === 4 ||
        item.attributeType === 5 ||
        item.attributeType === 2 ||
        item.attributeType === 8) &&
      item.editAble === 1
    ) {
      item.attributeValue = '';
      appEvents.trigger('clearImageList');
    }
  });
}

/**
 * 监听所有条件分支属性
 * 当所有条件分支属性填写完成后
 * 触发搜索
 */
function conditionAttributeChanged() {
  // 当所有条件分支属性填写完成后，触发搜索
  const condAttrList = state.attributes?.filter((item) => item.isCondition);
  const isAllConditionAttributeFull = condAttrList?.every((item) => item.attributeValue);
  if (isAllConditionAttributeFull && condAttrList && condAttrList.length > 0) {
    showLoading();
    QUERY_FLOW_BY_COND_ATTR({ id: state.templateId, condAttrList }).then((res) => {
      state.flowGraph = res.flowpathTemplateDto?.flowGraph;
      state.flowGraphAddFlow = res.flowpathTemplateDto?.flowGraphAddFlow;
    });
  }
}

function saveDraftByRequest() {
  showLoading();
  SAVE({
    userId: state.userId,
    flowpathRecordDto: {
      templateId: state.templateId,
      attributes: state.attributes,
    },
    flowGraph: state.flowGraph,
    flowGraphAddFlow: state.flowGraphAddFlow,
    flowGraphList: state.flowGraphList,
  }).then((res) => {
    if (res.comResp?.code === 100) {
      showModal({
        title: '保存草稿成功',
        showCancel: false,
        content: '下次进入申请页面可继续填写表单内容',
      });
    }
  });
}

function saveDraft() {
  if (state.userId) {
    saveDraftByRequest();
  } else {
    showLoading();
    LOGIN_APP().then((res) => {
      state.userId = res.sysUserDto.id;
      saveDraftByRequest();
    });
  }
}

function queryDraft(id: string) {
  showLoading();
  LOGIN_APP().then((res) => {
    state.userId = res.sysUserDto.id;
    FIND_ONE({ templateId: id, userId: state.userId }).then((res) => {
      if (res.flowpathRecordDto) {
        showModal({
          title: '继续填写',
          content: '你有未提交的内容，是否载入草稿继续填写？',
          success: function (result) {
            if (result.confirm) {
              setDraftAttributes(res.flowpathRecordDto?.attributes);
              state.flowGraph = res.flowGraph;
              state.flowGraphAddFlow = res.flowGraphAddFlow;
              state.flowGraphList = res.flowGraphList;
            } else if (result.cancel) {
              deleteDraft(id);
            }
          },
        });
      }
    });
  });
}

/**
 * 只修改attribute中的值
 */
function setDraftAttributes(attributes?: FlowPathTemplateApi.AttributeDto[]) {
  attributes?.forEach((attribute) => {
    const itemAttribute = state.attributes?.find(
      (item) => item.attributeCode === attribute.attributeCode,
    );
    if (itemAttribute) {
      itemAttribute.attributeValue = attribute.attributeValue;
    }
  });
}

function deleteDraft(id: string) {
  DELETE({ templateId: id, userId: state.userId });
}

/**
 * @function 获取审批详情
 */
function queryApprovedDetail(id: string) {
  showLoading();
  QUERY_APP_FLOW_PATH_RECORD_DETAIL({ id }).then((res) => {
    setDraftAttributes(res.flowpathRecordDto?.attributes);
  });
}

export {
  queryDetail,
  submit,
  conditionAttributeChanged,
  saveDraft,
  queryDraft,
  deleteDraft,
  submitByCustomSingle,
};
